#include <iostream>
#include <pthread.h>
#include <semaphore.h>


static int glob = 0;
static sem_t sem; // 定义一个信号量

void* threadFunc(void* args)
{
   int loops = *((int*)args);
   int loc, j;
   for(j = 0; j < loops; j++)
   {
        // 申请信号量：申请成功的线程，才能执行后续操作
        if(sem_wait(&sem) == -1)
            perror("sem_wait");
       loc = glob;
       loc++;
       glob = loc;
       // 释放信号量
       if(sem_post(&sem) == -1)
            perror("sem_post");
   }
   return nullptr;
}

int main(int argc, char* argv[])
{
   (void)argc;
   pthread_t t1, t2;
   int loops = std::stoi(argv[1]);

    // 初始化信号量
    if(sem_init(&sem, 0, 1) == -1)
        perror("sem_init");

   int s = pthread_create(&t1, nullptr, threadFunc, &loops);
   if(s != 0)
       perror("pthread_create_1");
   s = pthread_create(&t2, nullptr, threadFunc, &loops);
   if(s != 0)
       perror("pthread_create_2");

   s = pthread_join(t1, nullptr);
   if(s != 0)
       perror("pthread_join_1");
   s = pthread_join(t2, nullptr);
   if(s != 0)
       perror("pthread_join_2");
    // 销毁信号量
    sem_destroy(&sem);
   std::cout << "glob = " << glob << std::endl;
   return 0;
}